package com.openluat.LuatTestServer.webSocket;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;

@Service
@ServerEndpoint("/websocket")
@Slf4j
public class WebSocketServer {

    private Session session;

    @OnOpen
    public void onOpen(Session session) {
        this.session = session;
        log.info("[WebSocket]-open session " + session.getId());
    }

    @OnClose
    public void onClose() {
        log.info("[WebSocket]-close session " + session.getId());
    }

    @OnMessage
    public void onMessage(String message) {
        try {
            log.info("[Websocket]-" + session.getId() + " receive message: " + message);
            this.session.getBasicRemote().sendText(message);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @OnError
    public void onError(Throwable error) {
        error.printStackTrace();
    }

}